package com.mfsoft.camera;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Config;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.facebook.FacebookAuthorizationException;
import com.facebook.FacebookOperationCanceledException;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.FacebookDialog;
import com.facebook.widget.LoginButton;
import com.facebook.widget.LoginButton.UserInfoChangedCallback;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.common.Scopes;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.plus.PlusClient;
import com.google.android.gms.plus.model.people.Person;
import com.mfsoft.model.Account;
import com.mfsoft.model.UserActions;
import com.mfsoft.net.MyFunctions_THI;
import com.mfsoft.utilities.Utility;

public class LoginedActivity extends SherlockActivity implements
		OnClickListener, UserInfoChangedCallback, ConnectionCallbacks,
		OnConnectionFailedListener {

	private EditText edttendangnhap, edtpassword;
	private Button btndangnhap, btndangky;
	private ActionBar mActionBar;
	private CameraApp instance;
	private ProgressBar progressBar;
	private RelativeLayout layoutContent;
	/** setup Twitter api */
	private Button btn_Login_Twitter;
	/** setup Facebook api */
	private LoginButton btn_Login_Facebook;
	private UiLifecycleHelper uiHelper;
	private PendingAction pendingAction = PendingAction.NONE;
	private final String PENDING_ACTION_BUNDLE_KEY = "com.mfsoft.camera:PendingAction";
	private GraphUser userFacebook;
	private UserActions userActions;
	String prefname = "my_data";

	private enum PendingAction {
		NONE, POST_PHOTO, POST_STATUS_UPDATE
	}

	private Session.StatusCallback callback = new Session.StatusCallback() {
		@Override
		public void call(Session session, SessionState state,
				Exception exception) {
			onSessionStateChange(session, state, exception);
		}
	};

	/** Setup google+ api */
	private static final int REQUEST_CODE_RESOLVE_ERR = 9000;

	private ProgressDialog mConnectionProgressDialog;
	private PlusClient mPlusClient;
	private ConnectionResult mConnectionResult;
	private SignInButton btn_Login_Google;
	private Button btn_Logout_Google;

	private Handler handler = new Handler();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_logined_activity__thi);
		instance = (CameraApp) getApplicationContext();
		// get action bar
		mActionBar = getSupportActionBar();
		mActionBar.setDisplayShowHomeEnabled(false);
		mActionBar.setDisplayShowTitleEnabled(false);
		getControls();

		/** Facebook api */
		uiHelper = new UiLifecycleHelper(this, callback);
		uiHelper.onCreate(savedInstanceState);

		if (savedInstanceState != null) {
			String name = savedInstanceState
					.getString(PENDING_ACTION_BUNDLE_KEY);
			pendingAction = PendingAction.valueOf(name);
		}

		/** Google api */

		mPlusClient = new PlusClient.Builder(this, this, this)
				.setActions("http://schemas.google.com/AddActivity",
						"http://schemas.google.com/BuyActivity")
				.setScopes(Scopes.PLUS_LOGIN, Scopes.PLUS_PROFILE).build();
		// Progress bar to be displayed if the connection failure is not
		// resolved.
		mConnectionProgressDialog = new ProgressDialog(this);
		mConnectionProgressDialog.setMessage("Signing in...");

		/** anh xa */
		edttendangnhap = (EditText) findViewById(R.id.edttendangnhap);
		edtpassword = (EditText) findViewById(R.id.edtpassword);
		btndangnhap = (Button) findViewById(R.id.btndangnhap);
		btndangky = (Button) findViewById(R.id.btndangky);
		btn_Login_Facebook = (LoginButton) findViewById(R.id.btn_login_facebook);
		btn_Login_Google = (SignInButton) findViewById(R.id.btn_login_google);
		btn_Logout_Google = (Button) findViewById(R.id.btn_logout_google);
		progressBar = (ProgressBar) findViewById(R.id.pb_loading);
		layoutContent = (RelativeLayout) findViewById(R.id.layoutContent);
		/** action */
		btndangnhap.setOnClickListener(this);
		btndangky.setOnClickListener(this);
		btn_Login_Facebook.setReadPermissions(Arrays.asList("email",
				"user_birthday"));
		btn_Login_Facebook.setUserInfoChangedCallback(this);
		userActions = new UserActions(this, this);
		userActions.instance = instance;

		btn_Login_Google.setOnClickListener(this);
		setGooglePlusButtonText(btn_Login_Google,
				getResources().getString(R.string.google_login_button));
		btn_Logout_Google.setOnClickListener(this);
		// onResume();

	}

	private void getControls() {
		View custom = LayoutInflater.from(LoginedActivity.this).inflate(
				R.layout.customactionbar, null);
		ImageView ivLogo = (ImageView) custom
				.findViewById(R.id.menuViewButtonLogoactionbar);
		ImageView ivLogin = (ImageView) custom
				.findViewById(R.id.imageViewLoginactionbar);
		TextView tvTitle = (TextView) custom
				.findViewById(R.id.textViewTitleApp);
		View dvHeader2 = (View) custom
				.findViewById(R.id.header_vertical_divider_2);

		dvHeader2.setVisibility(View.GONE);
		ivLogin.setVisibility(View.GONE);
		ivLogo.setVisibility(View.GONE);
		tvTitle.setText(getResources().getString(R.string.actionbar_back));
		tvTitle.setPadding(10, 0, 0, 0);
		tvTitle.setTextColor(Color.parseColor("#FFFFFF"));
		tvTitle.setOnClickListener(this);
		mActionBar.setCustomView(custom);
		mActionBar.setDisplayShowCustomEnabled(true);
		mActionBar.setLogo(new ColorDrawable(Color.TRANSPARENT));
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);

		uiHelper.onSaveInstanceState(outState);

		outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name());
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		uiHelper.onActivityResult(requestCode, resultCode, data, dialogCallback);
		if (requestCode == REQUEST_CODE_RESOLVE_ERR && resultCode == RESULT_OK) {
			mConnectionResult = null;
			mPlusClient.connect();
		}
		if (requestCode == com.mfsoft.utilities.Config.requestLoginRegister
				&& resultCode == RESULT_OK) {
			final ProgressDialog progress = ProgressDialog.show(
					LoginedActivity.this, "",
					getResources().getString(R.string.logining), true);
			handler.postDelayed(new Runnable() {

				@Override
				public void run() {
					progress.dismiss();
					Intent returnIntent = new Intent();
					returnIntent.putExtra("user", "success");
					setResult(RESULT_OK, returnIntent);
					finish();
				}
			}, 2500);
		}
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		mPlusClient.connect();
	}

	@Override
	protected void onStop() {
		super.onStop();
		mPlusClient.disconnect();
	}

	@Override
	public void onPause() {
		super.onPause();
		uiHelper.onPause();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		uiHelper.onDestroy();
	}

	class thuthilogin extends AsyncTask<Void, Void, String> {

		MyFunctions_THI myfunction_thi;
		String username;
		String password;
		String thanhcong = null;
		private ProgressDialog progress;

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			progress = ProgressDialog.show(LoginedActivity.this, "",
					getResources().getString(R.string.logining), true);
		}

		@Override
		protected String doInBackground(Void... params) {
			// TODO Auto-generated method stub
			// doan nay thi ok kiem tra rui
			username = edttendangnhap.getText().toString();
			password = edtpassword.getText().toString();
			password = Utility.md5(password);
			try {
				{
					JSONObject jsonobject;

					myfunction_thi = new MyFunctions_THI(
							getApplicationContext());
					jsonobject = myfunction_thi.loginUser(username, password);
					thanhcong = jsonobject.toString();
				}

			} catch (Exception e) {
				Log.d("loi", "khong tao Json duoc" + e.toString());
			}
			
			return thanhcong;
		}

		@Override
		protected void onPostExecute(String thanhcong) {
			// TODO Auto-generated method stub
			super.onPostExecute(thanhcong);
			// JSONObject jsonobject = myfunction_thi.loginUser(username,
			// password);

			Log.d("log", thanhcong);
			// kiem tra no chuyen wa hay khong
			progress.dismiss();
			try {
				JSONObject jsonobject = new JSONObject(thanhcong);
				String result = jsonobject.getString("result");

				// cho nay sao cho khi no incorrect thi xuat thong bao loi
				// cho nay neu result no khac -1 chu ta
				if (result.equalsIgnoreCase("-1")) {// username or password is
													// incorrect
					AlertDialog.Builder alert = new AlertDialog.Builder(
							LoginedActivity.this);
					alert.setTitle(getResources().getString(
							R.string.errortitlelogin));
					alert.setMessage(getResources().getString(
							R.string.errormessagelogin));
					alert.setNeutralButton(LoginedActivity.this.getResources()
							.getString(R.string.ok),
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									setEditTextFocus(edttendangnhap, true);
								}
							});
					alert.show();
				} else {
					JSONObject infor = jsonobject.getJSONArray("result")
							.getJSONObject(0);
					Log.d(String.valueOf(jsonobject.getJSONArray("result")
							.getJSONObject(0)), "thongbao");
					
					String email = infor.getString(Account.key_gmail);
					String nickName = infor.getString(Account.key_nickname);
					String gender = infor.getString(Account.key_gender);
					String type = infor.getString(Account.key_type);
					String userName = infor.getString(Account.key_userName);
					String userId = infor.getString(Account.key_userId);
					String birthday = infor.getString(Account.key_birthday);

					Account account = new Account(email, userId, birthday,
							gender, userName, type, nickName);
					Utility.setAccount(LoginedActivity.this, account);
					Intent i = getIntent();
					i.putExtra("user", "success");
					setResult(1, i);
					finish();

				}
				/*
				 * if(thanhcong == jsonobject.getString("thanhcong")) // if
				 * (Integer.parseInt(thanhcong) == 1) // dang nhap thanh cong //
				 * { myfunction_thi.setUsernameLogin(username);// muc dich luu
				 * lai // ten cho lan sau SharedPreferences lay =
				 * getPreferences(MODE_WORLD_READABLE); username =
				 * lay.getString("username", username); password =
				 * lay.getString("password", password);
				 * edttendangnhap.setText(username);
				 * edtpassword.setText(password); lay.edit();
				 * 
				 * Intent i = new Intent(getApplicationContext(),
				 * LoginedActivity.class); startActivity(i); finish();
				 * 
				 * } else // neu that bai {
				 * Toast.makeText(getApplicationContext(),
				 * "usernam or password sai", Toast.LENGTH_SHORT).show(); }
				 */
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	public void setEditTextFocus(EditText et, boolean isFocused) {
		et.setCursorVisible(isFocused);
		et.setFocusable(isFocused);
		et.setFocusableInTouchMode(isFocused);

		if (isFocused) {
			et.requestFocus();
		}
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY); // show
	}

	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		switch (view.getId()) {
		case R.id.btndangnhap:
			onLogin();
			break;
		case R.id.btndangky:
			onRegister();
			break;
		case R.id.btn_login_google:
			onLoginGoogle();
			break;
		case R.id.btn_logout_google:
			onLogoutGoogle();
			break;
		case R.id.textViewTitleApp:
			Intent i = new Intent(this, MainActivity.class);
			startActivity(i);
			finish();
			break;
		}
	}

	/*
	 * @Override protected void onResume() { // TODO Auto-generated method stub
	 * super.onResume(); //gọi hàm đọc trạng thái ở đây restoringPreferences();
	 * new thuthilogin().execute(); }
	 *//**
	 * hàm đọc trạng thái đã lưu trước đó
	 */
	/*
	 * public void restoringPreferences() { SharedPreferences
	 * pre=getSharedPreferences (prefname,MODE_PRIVATE); //lấy giá trị checked
	 * ra, nếu không thấy thì giá trị mặc định là false
	 * 
	 * //lấy user, pwd, nếu không thấy giá trị mặc định là rỗng String
	 * user=pre.getString("user", ""); String pass=pre.getString("pass", "");
	 * edttendangnhap.setText(user); edtpassword.setText(pass);
	 * 
	 * 
	 * }
	 */
	private void onLogin() {
		if (edttendangnhap.getText().toString().equals(""))
			edttendangnhap.setError("Nhap ten nguoi dung");
		else if (edttendangnhap.getText().toString().length() < 6)
			edttendangnhap.setError("Nhap ten >=6");

		else if (edtpassword.getText().toString().equals(""))
			edtpassword.setError("Nhap password");
		else if (edtpassword.getText().toString().length() < 6)
			edtpassword.setError("Nhap password >=6");
		else
			new thuthilogin().execute();
	}

	private void onRegister() {
		Intent i = new Intent(getApplicationContext(), RegisterActivity.class);
		startActivityForResult(i,
				com.mfsoft.utilities.Config.requestLoginRegister);
		// finish();
	}

	/** Facebook api */
	@Override
	public void onUserInfoFetched(GraphUser user) {
		// TODO Auto-generated method stub
		layoutContent.setVisibility(View.GONE);
		progressBar.setVisibility(View.VISIBLE);
		userFacebook = user;
		updateUI();
	}

	private void onSessionStateChange(Session session, SessionState state,
			Exception exception) {
		if (pendingAction != PendingAction.NONE
				&& (exception instanceof FacebookOperationCanceledException || exception instanceof FacebookAuthorizationException)) {
			new AlertDialog.Builder(LoginedActivity.this)
					.setTitle(R.string.cancelled)
					.setMessage(R.string.permission_not_granted)
					.setPositiveButton(R.string.ok, null).show();
			pendingAction = PendingAction.NONE;
		}
		updateUI();
	}

	private void updateUI() {
		Session session = Session.getActiveSession();
		boolean isLogined = (session != null && session.isOpened());

		if (isLogined && userFacebook != null) {
			Date date = new Date(userFacebook.getBirthday().toString());
			SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
			String birthday = fmt.format(date);
			// Log.w("userFacebook", "gmail:" +
			// userFacebook.getProperty("email") + "username:" +
			// userFacebook.getUsername() + ","
			// + " birthday:" + birthday + ", gender:" +
			// userFacebook.getProperty("gender") + ","
			// + " Display name:" + userFacebook.getName());
			String gender = null;
			String avatar = "http://graph.facebook.com/" + userFacebook.getId()
					+ "/picture?type=small";
			if (userFacebook.getProperty("gender").toString()
					.equalsIgnoreCase("male")) {
				gender = "1";
			} else {
				gender = "0";
			}
			HashMap<String, String> data = new HashMap<String, String>();
			data.put(UserActions.GMAIL, userFacebook.getProperty("email")
					.toString());
			data.put(UserActions.USERNAME, userFacebook.getUsername()
					.toString());
			data.put(UserActions.BIRTHDAY, birthday);
			data.put(UserActions.GENDER, gender);
			data.put(UserActions.NICKNAME, userFacebook.getName());
			data.put(UserActions.AVATAR, avatar);
			data.put(UserActions.TYPE, "facebook");

			userActions.LoginSocial(data);
		} else {
			layoutContent.setVisibility(View.VISIBLE);
			progressBar.setVisibility(View.GONE);
			instance.cameraModel.logoutSocial();
		}
	}

	private FacebookDialog.Callback dialogCallback = new FacebookDialog.Callback() {
		@Override
		public void onError(FacebookDialog.PendingCall pendingCall,
				Exception error, Bundle data) {
			Log.d("HelloFacebook", String.format("Error: %s", error.toString()));
		}

		@Override
		public void onComplete(FacebookDialog.PendingCall pendingCall,
				Bundle data) {
			Log.d("HelloFacebook", "Success!");
		}
	};

	/** Google plus api */
	protected void setGooglePlusButtonText(SignInButton signInButton,
			String buttonText) {
		// Find the TextView that is inside of the SignInButton and set its text
		for (int i = 0; i < signInButton.getChildCount(); i++) {
			View v = signInButton.getChildAt(i);

			if (v instanceof TextView) {
				TextView tv = (TextView) v;
				tv.setText(buttonText);
				return;
			}
		}
	}

	private void onLoginGoogle() {
		if (mConnectionResult == null) {
			mConnectionProgressDialog.show();
		} else {
			try {
				mConnectionResult.startResolutionForResult(this,
						REQUEST_CODE_RESOLVE_ERR);
			} catch (SendIntentException e) {
				// Try connecting again.
				mConnectionResult = null;
				mPlusClient.connect();
			}
		}
	}

	private void onLogoutGoogle() {
		if (mPlusClient.isConnected()) {
			mPlusClient.clearDefaultAccount();
			mPlusClient.disconnect();
			// mPlusClient.connect();
		}
		instance.cameraModel.logoutSocial();
	}

	@Override
	public void onConnectionFailed(ConnectionResult result) {
		// TODO Auto-generated method stub
		if (mConnectionProgressDialog.isShowing()) {
			// The user clicked the sign-in button already. Start to resolve
			// connection errors. Wait until onConnected() to dismiss the
			// connection dialog.
			if (result.hasResolution()) {
				try {
					result.startResolutionForResult(this,
							REQUEST_CODE_RESOLVE_ERR);
				} catch (SendIntentException e) {
					mPlusClient.connect();
				}
			}
		}

		// Save the intent so that we can start an activity when the user clicks
		// the sign-in button.
		mConnectionResult = result;
		updateButtons(false);
	}

	@Override
	public void onConnected(Bundle arg0) {
		// TODO Auto-generated method stub
		updateButtons(true);
		mConnectionProgressDialog.dismiss();
		layoutContent.setVisibility(View.GONE);
		progressBar.setVisibility(View.VISIBLE);
		// Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();
		Person person = mPlusClient.getCurrentPerson();
		// Log.w("data user", "gmail:" + mPlusClient.getAccountName() +
		// ", username:" + mPlusClient.getAccountName() + ","
		// + " birthday:" + person.getBirthday() + ", gender:" +
		// person.getGender() + ","
		// + " Display name:" + person.getDisplayName() + ", nickname: " +
		// person.getNickname());
		String avatar = "";
		String gender = "";
		String birthday = "";
		String nickname = "";
		if (person != null) {
			if (person.hasGender()) {
				if (person.getGender() == 0) {
					gender = "1";
				} else {
					gender = "0";
				}
			}

			if (person.hasBirthday()) {
				birthday = person.getBirthday();
			}

			if (person.hasDisplayName()) {
				nickname = person.getDisplayName();
			}

			if (person.hasImage()) {
				avatar = person.getImage().getUrl();
			}
			HashMap<String, String> data = new HashMap<String, String>();
			data.put(UserActions.GMAIL, mPlusClient.getAccountName().toString());
			data.put(UserActions.USERNAME, mPlusClient.getAccountName()
					.toString());
			data.put(UserActions.BIRTHDAY, birthday);
			data.put(UserActions.GENDER, gender);
			data.put(UserActions.NICKNAME, nickname);
			data.put(UserActions.AVATAR, avatar);
			data.put(UserActions.TYPE, "google");

			userActions.LoginSocial(data);
		}
	}

	@Override
	public void onDisconnected() {
		// TODO Auto-generated method stub
		updateButtons(false);
	}

	private void updateButtons(boolean isSignedIn) {
		if (isSignedIn) {
			btn_Login_Google.setVisibility(View.GONE);
			btn_Logout_Google.setVisibility(View.VISIBLE);
		} else {
			if (mConnectionResult == null) {
				// Disable the sign-in button until onConnectionFailed is called
				// with result.
				btn_Login_Google.setVisibility(View.GONE);
			} else {
				// Enable the sign-in button since a connection result is
				// available.
				btn_Login_Google.setVisibility(View.VISIBLE);
			}

			btn_Logout_Google.setVisibility(View.GONE);
		}
	}
}
